import java.io.BufferedReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class ServerThread extends Thread {
	
    protected DatagramSocket socket = null;
    protected BufferedReader in = null;

    public ServerThread() throws IOException {
	this("QuoteServerThread");
    }

    public ServerThread(String name) throws IOException {
        super(name);
        socket = new DatagramSocket(4445);
    }

    public void run() {
    	boolean morePackets = true;

    	int numRecdPackets = 0;
    	int[] recdPackets = new int[MyServer.EXP_NUM_PACKETS];
    	DatagramPacket packet = null;
    	byte[] buf = null;
        try {
	        while (numRecdPackets < MyServer.EXP_NUM_PACKETS) {
	                buf = new byte[256];
	
	                    // receive request
	                packet = new DatagramPacket(buf, buf.length);
	                socket.receive(packet);
	                numRecdPackets++;
	                
	                PacketData packetData = getPacketData(packet);
	                recdPackets[packetData.seq] = packetData.value;
	        }
	        
	        
	        System.out.println("----------------> Server Received Packets:");
	        for (int i=0; i<recdPackets.length; i++)
	        	System.out.println((i+1) + ", " + recdPackets[i]);
	        
	        	// send the response to the client at "address" and "port"
	        byte[] resp = "RECEIVE_SUCCESS".getBytes();
	        InetAddress address = packet.getAddress();
	        int port = packet.getPort();
	        packet = new DatagramPacket(resp, resp.length, address, port);
	        socket.send(packet);
	        	
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
        	socket.close();
        }
    }

    
    private PacketData getPacketData(DatagramPacket packet) {
    	byte[] byToIn = packet.getData();
    	
    	int newSeq = 0;
		newSeq = (0xff & byToIn[7]) << 56;
		newSeq |= (0xff & byToIn[6])<< 48;
		newSeq |= (0xff & byToIn[5])<< 40;
		newSeq |= (0xff & byToIn[4])<< 32;
		
		int newVal = 0;
		newVal = (0xff & byToIn[3])<< 24;
		newVal |= (0xff & byToIn[2])<< 16;
		newVal |= (0xff & byToIn[1])<< 8;
		newVal |= (0xff & byToIn[0]);	
		
		return new PacketData(newSeq, newVal);
    }
    
    
    class PacketData 
    {
    	int seq = -1;
    	int value = 0;
    	
    	PacketData(int s, int v) {
    		seq = s;
    		value = v;
    	}
    }
}
